package org.example.todoapp;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.time.LocalDateTime;

@CrossOrigin
@RestController
@RequestMapping("/todo")
public class TaskController {
    private final Db db;

    @Autowired
    public TaskController(Db db) {
        this.db = db;
    }

    @GetMapping("")
    public Object list() throws SQLException {
        return db.query("select * from task order by id desc", Task.class);
    }
    @PostMapping("")
    public Object add(@RequestBody Task task) throws SQLException {
        task.setId(null);
        task.setCreated_at(LocalDateTime.now());
        db.insert(Entity.parse(task));
        return "ok";
    }
    @PutMapping("/{id}")
    public Object update(@PathVariable Integer id) throws SQLException {
        return db.execute("update task set completed = 1 - completed where id = ?", id);
    }
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Integer id) throws SQLException {
        return db.del("task","id",id);
    }
}
